package com.clss.commandhelper.function.newEvidence;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.Spinner;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.clss.commandhelper.CommandHelperApplication;
import com.clss.commandhelper.R;
import com.clss.commandhelper.base.BaseActivity;
import com.clss.commandhelper.function.casedetail.CaseDetailActivity;
import com.clss.commandhelper.tools.Constant;
import com.clss.commandhelper.tools.MediaManager;
import com.clss.commandhelper.tools.SpHelper;
import com.clss.commandhelper.tools.UploadHelper;
import com.clss.commandhelper.tools.Utils;
import com.clss.commandhelper.view.RecordButton;
import com.clss.commandhelper.view.listbottomsheetdialog.BottomSheetDialogUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static com.clss.commandhelper.tools.Constant.REQUEST_CODE_CAMARE;
import static com.clss.commandhelper.tools.Constant.REQUEST_CODE_IMAGE;
import static com.clss.commandhelper.tools.Constant.REQUEST_CODE_VIDEO;

public class EvidenceAndNewCaseActivity extends BaseActivity implements TaskAudioAdapter.OnChildItemClickListener,
        AdapterView.OnItemClickListener, EvidenceAndNewCasePresenter.CaseView, RecordButton.OnFinishedRecordListener {

    @BindView(R.id.task_content)
    EditText taskContent;
//    @BindView(R.id.task_sp_level)
//    Spinner taskSpLevel;
//    @BindView(R.id.spinner_level_layout)
//    LinearLayout spinnerLevelLayout;
    //    @BindView(R.id.task_sp_type)
//    Spinner taskSpType;
//    @BindView(R.id.spinner_type_layout)
//    LinearLayout spinnerTypeLayout;
//    @BindView(R.id.task_sp_police_level)
//    Spinner taskSpPoliceLevel;
//    @BindView(R.id.spinner_police_level_layout)
//    LinearLayout spinnerPoliceLevelLayout;
    @BindView(R.id.task_rv_img_video)
    RecyclerView taskRvImgVideo;
    @BindView(R.id.task_rv_audio)
    RecyclerView taskRvAudio;
    @BindView(R.id.task_audio_record_button)
    RecordButton recordButton;
    @BindView(R.id.include_top_bar_left_iv)
    ImageView includeTopBarLeftIv;
    @BindView(R.id.include_top_bar_title_tv)
    TextView includeTopBarTitleTv;
    @BindView(R.id.include_top_bar_right_iv)
    ImageView includeTopBarRightIv;
    @BindView(R.id.task_commit)
    Button taskCommit;

    String[] selectData = {"拍照", "图片", "视频"};
//    @BindView(R.id.task_unit_province)
//    RadioButton mTaskUnitProvince;
//    @BindView(R.id.task_unit_city)
//    RadioButton mTaskUnitCity;
//    @BindView(R.id.task_unit_area)
//    RadioButton mTaskUnitArea;
//    @BindView(R.id.task_unit_type_layout)
//    LinearLayout mTaskUnitTypeLayout;
    private int audioMax = 9;

    private ArrayList<TaskPoliceFile> imgs;
    private ArrayList<TaskPoliceFile> videos;
    private List<TaskPoliceFile> audioData;
    private List<TaskPoliceFile> multimedia;
    private List<TaskPoliceFile> data;

    GridImageAdapter adapterMultimedia;
    TaskAudioAdapter audioAdapter;
    private GridImageAdapter.onAddPicClickListener onAddPicClickListener;

    private InfoTaskDispatch infoTaskDispatch;
    private int type;
    private AMapLocation location;
    public static final int NEWTASK = 1;
    public static final int COLLECT = 2;

    private EvidenceAndNewCasePresenter presenter;

    @Override
    protected int setViewId() {
        return R.layout.activity_evidence_and_new_case;
    }

    @Override
    protected void initView() {
        Bundle bundle = getIntent().getExtras();
        type = bundle.getInt("type", 0);
        if (type == COLLECT) {
            includeTopBarTitleTv.setText("现场取证");
            infoTaskDispatch = (InfoTaskDispatch) bundle.getSerializable("info");
        }else if (type == NEWTASK){
            includeTopBarTitleTv.setText("新建事件");
        }else {
            showShortToast("状态获取失败");
            finish();
        }
        location = CommandHelperApplication.getMapLocation();
        if (location == null || location.getLatitude() < 1) {
            showShortToast("定位失败，请定位成功后重试");
            finish();
            return;
        }
        imgs = new ArrayList<>();
        videos = new ArrayList<>();
        audioData = new ArrayList<>();
        multimedia = new ArrayList<>();
        data = new ArrayList<>();
        presenter = new EvidenceAndNewCasePresenter();
        presenter.setCaseView(this);
        recordButton.setOnFinishedRecordListener(this);
    }

    @Override
    protected void initData(@Nullable Bundle savedInstanceState) {
        initMediaRv();
        initAudioRv();
    }

    private void initAudioRv() {
        audioAdapter = new TaskAudioAdapter(this, audioData);
        audioAdapter.setMax(9);
        audioAdapter.setOnChildItemClickListener(this);
        audioAdapter.setOnItemClickListener(this);
        GridLayoutManager layoutManager = new GridLayoutManager(this, 4, GridLayoutManager.VERTICAL, false);
        taskRvAudio.setLayoutManager(layoutManager);
        taskRvAudio.setAdapter(audioAdapter);
    }

    private void initMediaRv() {
        onAddPicClickListener = getOnAddPicClickListener();
        taskRvImgVideo.setLayoutManager(new GridLayoutManager(this, 4, GridLayoutManager.VERTICAL, false));
        adapterMultimedia = new GridImageAdapter(this, onAddPicClickListener);
        adapterMultimedia.setAddImg(R.mipmap.btn_add);
        adapterMultimedia.setSelectMax(9);
        taskRvImgVideo.setAdapter(adapterMultimedia);
        adapterMultimedia.setList(multimedia);

        adapterMultimedia.setOnItemClickListener((position, v) -> {
            if (position != multimedia.size()) {
                int type = multimedia.get(position).getType();
                switch (type) {
                    case 14:
                        File file = new File(multimedia.get(position).getName());
                        Intent it = new Intent(Intent.ACTION_VIEW);
                        Uri mUri = Uri.parse("file://" + file.getPath());
                        it.setDataAndType(mUri, "image/*");
                        startActivity(it);
                        break;
                    case 15:
                        Utils.openLocalVideo(this, multimedia.get(position).getName());
                        break;
                        default:
                }
            }
        });
    }

    private GridImageAdapter.onAddPicClickListener getOnAddPicClickListener(){
        return (type, position) -> {
            switch (type) {
                case 0:
                    showSelectDialog();
                    break;
                case 1:
                    // 删除图片
                    if (multimedia.get(position).getType() == 14) {
                        for (int i = 0; i < imgs.size(); i++) {
                            if (multimedia.get(position).getName().equals(imgs.get(i).getName())) {
                                imgs.remove(i);
                            }
                        }
                    } else if (multimedia.get(position).getType() == 15) {
                        for (int i = 0; i < videos.size(); i++) {
                            if (multimedia.get(position).getName().equals(videos.get(i).getName())) {
                                videos.remove(i);
                            }
                        }
                    }
                    multimedia.remove(position);
                    adapterMultimedia.notifyItemRemoved(position);
                    break;
                    default:
            }
        };
    }

    private void showSelectDialog() {
        BottomSheetDialogUtil.init(this, selectData,
                (v, position) -> {
                    switch (position) {
                        case 0:
                            getImageFromCaramer();
                            break;
                        case 1:
                            chooseLocImage();
                            break;
                        case 2:
                            Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Video.Media.EXTERNAL_CONTENT_URI);
                            startActivityForResult(intent, Constant.REQUEST_CODE_VIDEO);
                            break;
                            default:
                    }
                }).show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            String path = "";
            switch (requestCode) {
                case REQUEST_CODE_IMAGE:
                    path = UploadHelper.getImageAbsolutePath(this, data.getData());
                    TaskPoliceFile taskPoliceFile = new TaskPoliceFile();
                    taskPoliceFile.setName(path);
                    taskPoliceFile.setAddress(location.getAddress());
                    taskPoliceFile.setLatlng(location.getLatitude() + "," + location.getLongitude());
                    taskPoliceFile.setType(14);
                    taskPoliceFile.setTime(Utils.getNowTime());
                    imgs.add(taskPoliceFile);
                    multimedia.add(taskPoliceFile);
                    adapterMultimedia.notifyItemChanged(multimedia.size() - 1);
                    break;
                case REQUEST_CODE_CAMARE:
                    TaskPoliceFile taskPoliceFile1 = new TaskPoliceFile();
                    taskPoliceFile1.setName(mCamareFile.getPath());
                    taskPoliceFile1.setAddress(location.getAddress());
                    taskPoliceFile1.setLatlng(location.getLatitude() + "," + location.getLongitude());
                    taskPoliceFile1.setType(14);
                    taskPoliceFile1.setTime(Utils.getNowTime());
                    imgs.add(taskPoliceFile1);
                    multimedia.add(taskPoliceFile1);
                    adapterMultimedia.notifyItemChanged(multimedia.size() - 1);
                    break;
                case REQUEST_CODE_VIDEO:
                    Uri uri = data.getData();
                    Cursor cursor = getContentResolver().query(uri, null, null,
                            null, null);
                    if (cursor != null) {
                        if (cursor.moveToFirst()) {
                            String vPath = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA));
                            TaskPoliceFile taskPoliceFile2 = new TaskPoliceFile();
                            taskPoliceFile2.setName(vPath);
                            taskPoliceFile2.setAddress(location.getAddress());
                            taskPoliceFile2.setLatlng(location.getLatitude() + "," + location.getLongitude());
                            taskPoliceFile2.setType(15);
                            taskPoliceFile2.setTime(Utils.getNowTime());
                            videos.add(taskPoliceFile2);
                            multimedia.add(taskPoliceFile2);
                            cursor.close();
                            adapterMultimedia.notifyItemChanged(multimedia.size() - 1);
                        }
                    }
//                    String p = data.getExtras().getString("url");
//                    int type = data.getExtras().getInt("type", 0);
//                    if (!TextUtils.isEmpty(p)) {
//                        if (type == 1) {
//                            TaskPoliceFile taskPoliceFile2 = new TaskPoliceFile();
//                            taskPoliceFile2.setName(p);
//                            taskPoliceFile2.setAddress(location.getAddress());
//                            taskPoliceFile2.setLatlng(location.getLatitude() + "," + location.getLongitude());
//                            taskPoliceFile2.setType(14);
//                            taskPoliceFile2.setTime(Utils.getNowTime());
//                            imgs.add(taskPoliceFile2);
//                            multimedia.add(taskPoliceFile2);
//                        } else if (type == 2) {
//                            TaskPoliceFile taskPoliceFile2 = new TaskPoliceFile();
//                            taskPoliceFile2.setName(p);
//                            taskPoliceFile2.setAddress(location.getAddress());
//                            taskPoliceFile2.setLatlng(location.getLatitude() + "," + location.getLongitude());
//                            taskPoliceFile2.setType(15);
//                            taskPoliceFile2.setTime(Utils.getNowTime());
//                            videos.add(taskPoliceFile2);
//                            multimedia.add(taskPoliceFile2);
//                        }
//                        adapterMultimedia.notifyItemChanged(multimedia.size() - 1);
//
//                    }
                    break;
                    default:
            }
        }
    }

    @Override
    public void responseError(int code, String msg) {
        showShortToast(msg);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onChildItemClick(View view, int position) {
        switch (view.getId()) {
            case R.id.item_audio_del:
                audioData.remove(position);
                audioAdapter.removeItemState(position);
                break;
                default:
        }
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
        if (audioData.size() < audioMax && audioData.size() == position) {
            return;
        }
        List<Integer> itemState = audioAdapter.getItemState();
        if (itemState.get(position) == TaskAudioAdapter.stop) {
            MediaManager.playstop();
            audioAdapter.setStartToStop();
            playMedia(position);
        } else if (itemState.get(position) == TaskAudioAdapter.start) {
            MediaManager.playstop();
            audioAdapter.setItemState(position, TaskAudioAdapter.stop);
        }
    }

    @Override
    public void postSuccess(String taskId,String dispatchId) {
        showShortToast("提交成功");
        if (type == NEWTASK){
            Bundle bundle = new Bundle();
            bundle.putString(CaseDetailActivity.TASK_ID, taskId);
            bundle.putString(CaseDetailActivity.ID, dispatchId);
            Utils.startActivity(this, CaseDetailActivity.class, bundle);
            finish();
        }
        taskContent.setText("");
        data.clear();
        multimedia.clear();
        videos.clear();
        imgs.clear();
        audioData.clear();
        adapterMultimedia.notifyDataSetChanged();
        audioAdapter.notifyDataSetChanged();

    }

    @Override
    public void postFailure() {
        showShortToast("提交失败");
    }

    @Override
    public int getType() {
        return type;
    }

    @OnClick({R.id.task_audio_record_button, R.id.task_commit, R.id.include_top_bar_left_iv})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.task_audio_record_button:
                recordButton.initDialogAndStartRecord();
                break;
            case R.id.task_commit:
                commitEvidence();
                break;
            case R.id.include_top_bar_left_iv:
                finish();
                break;
            default:
                break;
        }
    }

    private void commitEvidence() {
        data.clear();
        if (type == NEWTASK) {
            if (location == null) {
                showShortToast("定位失败，请检查手机GPS是否开启");
                return;
            }
            infoTaskDispatch = new InfoTaskDispatch();
            infoTaskDispatch.setCreateTime(Utils.getNowTime());
            infoTaskDispatch.setAreaCode(location.getAdCode());
            infoTaskDispatch.setPoliceUserId(SpHelper.getInstance().getUserId());
            infoTaskDispatch.setPoliceInfoAddress(location.getAddress());
            infoTaskDispatch.setPoliceInfoLat(String.valueOf(location.getLatitude()));
            infoTaskDispatch.setPoliceInfoLng(String.valueOf(location.getLongitude()));
            if (taskContent.getText() != null && taskContent.getText().toString().trim().length() != 0){
                infoTaskDispatch.setPoliceInfoComment(taskContent.getText().toString().trim());
            }
//            if (taskContent.getText() != null && taskContent.getText().toString().trim().length() != 0) {
//                TaskPoliceFile taskPoliceFile = new TaskPoliceFile();
//                taskPoliceFile.setContent(taskContent.getText().toString());
//                taskPoliceFile.setTime(Utils.getNowTime());
//                taskPoliceFile.setType(1);
//                if (location != null) {
//                    taskPoliceFile.setAddress(location.getAddress());
//                    taskPoliceFile.setLatlng(location.getLatitude() + "," + location.getLongitude());
//                }
//                data.add(taskPoliceFile);
//            }
        } else if (type == COLLECT) {
            infoTaskDispatch.setCreateTime(Utils.timeToDate(infoTaskDispatch.getCreateTime()));
            if (taskContent.getText() != null && taskContent.getText().toString().trim().length() != 0) {
                TaskPoliceFile taskPoliceFile = new TaskPoliceFile();
                taskPoliceFile.setContent(taskContent.getText().toString());
                taskPoliceFile.setTime(Utils.getNowTime());
                taskPoliceFile.setType(1);
                if (location != null) {
                    taskPoliceFile.setAddress(location.getAddress());
                    taskPoliceFile.setLatlng(location.getLatitude() + "," + location.getLongitude());
                }
                data.add(taskPoliceFile);
            }
        }
        data.addAll(multimedia);
        data.addAll(audioData);

        presenter.upLoadFile(data, infoTaskDispatch);
    }

    /**
     * 录音结束监听
     * @param audioPath
     * @param fileName
     * @param duration
     */
    @Override
    public void onFinishedRecord(String audioPath, String fileName, int duration) {
        TaskPoliceFile taskPoliceFile = new TaskPoliceFile();
        taskPoliceFile.setName(audioPath);
        taskPoliceFile.setRecordTimeLength(duration);
        taskPoliceFile.setAudioTime(duration);
        taskPoliceFile.setType(28);
        taskPoliceFile.setTime(Utils.getNowTime());
        if (location != null) {
            taskPoliceFile.setAddress(location.getAddress());
            taskPoliceFile.setLatlng(location.getLatitude() + "," + location.getLongitude());
        }
        audioData.add(taskPoliceFile);
        audioAdapter.notifyItemChanged(audioData.size() - 1);
        if (audioData.size() == audioMax){
            recordButton.setVisibility(View.GONE);
        }else {
            recordButton.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 取消录音
     */
    @Override
    public void onCancelRecord() {
        showShortToast("取消录音");
    }

    /**
     * 播放内容详情的音频
     *
     */
    private void playMedia(int position) {
        audioAdapter.setStartToStop();
        audioAdapter.setItemState(position, TaskAudioAdapter.start);
        MediaManager.playSound(audioData.get(position).getName(), mp -> audioAdapter.setItemState(position, TaskAudioAdapter.stop));
    }

}
